#include <iostream>
#include "protocol.hpp"
#include <string>
#include <strings.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <memory>

namespace Client
{
    using namespace std;

    class udpClient
    {
    public:
        udpClient(const string &serverip, const uint16_t &serverport)
            : _serverip(serverip), _serverport(serverport), _sockfd(-1), _quit(false)
        {
        }
        void initClient()
        {
            // 创建socket
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                cerr << "socket error: " << errno << " : " << strerror(errno) << endl;
                exit(2);
            }
            cout << "socket success: " << " : " << _sockfd << endl;
        }
        void start()
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            server.sin_port = htons(_serverport);


            string inbuff;
            
            while(1)
            {
                Request req;
                string context;
                req.serialize(&context);
                string send_str = enLength(context);
                cout << "send string: " << send_str << endl;
                send(_sockfd, send_str.c_str(), send_str.size(), 0);

                string package, text;
                if(!recvPackage(_sockfd, inbuff, &package))
                    continue;
                if(!deLength(package, &text))
                    continue;
                Response res;
                res.deserialize(text);
                
                cout << "time now : " << res.time << endl;

            }
        }
        // Request Parse(string& input)
        // {
        //     // unsigned int seconds_since_1900 = ntohl(ntp_response.transmit_timestamp[0]);
        //     // unsigned int fraction = ntohl(ntp_response.transmit_timestamp[1]);
        //     // time_t timestamp = seconds_since_1900 - 2208988800UL;
        //     // printf("NTP server time: %s", ctime(&timestamp));
        // }
        ~udpClient()
        {
        }

    private:
        int _sockfd;
        string _serverip;
        uint16_t _serverport;
        bool _quit;
    };
} // namespace Client